var tgd = tgd || {};
tgd.Utilities = tgd.Utilities || {};
tgd.Utilities.Stopwatch = tgd.Utilities.Stopwatch || {};
tgd.Utilities.Stopwatch.Views = tgd.Utilities.Stopwatch.Views || {};

tgd.Utilities.Stopwatch.Views.HTMLTimer = function (canvas, timer, onCloseCallback) {
	this._updateTitle = false;
	this._isClosed = false;
	this._timer = timer;
	this._canvas = canvas;

	var self = this;
	var headerDiv = document.createElement("div");
	var newTimerDiv = document.createElement("div");
	var titleSpan = document.createElement("span");
	var endSpan = document.createElement("span");
	var deleteButton = document.createElement("span");

	newTimerDiv.className = "timerDigits";
	headerDiv.className = "timerHeader"
	deleteButton.className = "timerButton";
	titleSpan.className = "timerTitle";
	endSpan.className = "timerEnds";

	this._canvas.appendChild(headerDiv);
	this._canvas.appendChild(newTimerDiv);
	headerDiv.appendChild(deleteButton);
	headerDiv.appendChild(titleSpan);
	headerDiv.appendChild(endSpan);

	titleSpan.innerHTML = decodeURI(self._timer.getTitle());
	endSpan.innerHTML = "[" + self._timer.getEndDateTime() + "]";  //todo: this may change when dates are implemented
	deleteButton.innerHTML = "X";
	deleteButton.title = "Delete";
	deleteButton.onclick = function() { self._isClosed = true; onCloseCallback() };

	self._timer.onTimerExpired = function() {
		self._canvas.className = "finished";
	}

	self._timer.onUpdate = function() {
		newTimerDiv.innerHTML = self._timer;
		if (self._updateTitle) {
			document.title = decodeURI(self._timer.toString(true));
		}
	};

	self._timer.start();

	if (tgd.Utilities.Stopwatch.Views.HTMLTimer._initialized === undefined) {

		tgd.Utilities.Stopwatch.Views.HTMLTimer.prototype.setUpdateTitle = function(update) {
			this._updateTitle = update;
		}

		tgd.Utilities.Stopwatch.Views.HTMLTimer.prototype.isClosed = function() {
			return this._isClosed;
		}

		tgd.Utilities.Stopwatch.Views.HTMLTimer.prototype.getTimer = function() {
			return this._timer;
		}

		tgd.Utilities.Stopwatch.Views.HTMLTimer.prototype.getCanvas = function() {
			return this._canvas;
		}

		tgd.Utilities.Stopwatch.Views.HTMLTimer._initialized = true;
	}
};